package cn.wit.summit.chwan.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.AllNetHotGameAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameInfoDetialV2Bean;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.AllNetHotGameResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.activity.AllNetHotGameActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStrokeV2Big;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/7/14.
 */

public class AllNetHotGameFragment extends BaseFragment {

    @Bind(R.id.imageListFragmentRv)
    RecyclerView imageListFragmentRv;
    @Bind(R.id.numberTv)
    TextView numberTv;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private AllNetHotGameAdapter adapter;
    private List<AllNetHotGameAdapter.ViewBean> mDatas = new ArrayList<>();
    private LinearLayoutManager layoutManager;

    private int typeId;
    private boolean isFisrt;
    private AllNetHotGameResponse mAllNetHotGameResponse;

    public static AllNetHotGameFragment newInstance(int typeId, boolean isFisrt) {
        Bundle args = new Bundle();
        args.putInt("typeId", typeId);
        args.putBoolean("isFisrt", isFisrt);
        AllNetHotGameFragment fragment = new AllNetHotGameFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_allnet_hotgame, null);
        ButterKnife.bind(this, view);


        typeId = getArguments().getInt("typeId", 0);
        isFisrt = getArguments().getBoolean("isFisrt", false);
        if (typeId==1) {
            numberTv.setText(" Top 30 ");
        } else {
            numberTv.setText(" Top 50 ");
        }

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        adapter = new AllNetHotGameAdapter(getActivity(), mDatas, typeId);
        layoutManager = new LinearLayoutManager(getActivity());
        imageListFragmentRv.setLayoutManager(layoutManager);
        imageListFragmentRv.setAdapter(adapter);

        if (isFisrt) {
            getData();
        }

        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getActivity()!=null && isVisibleToUser && !isFisrt && mAllNetHotGameResponse==null) {
            getData();
        }
        if (mAllNetHotGameResponse!=null)
            changeShowRefreshTime(mAllNetHotGameResponse.getLastTime());
    }

    private void changeShowRefreshTime(String lastTime) {
        if (getActivity()!=null) {
            ((AllNetHotGameActivity)getActivity()).setAllHotGameRefreshTimeTv(lastTime);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void getData() {
        api.getAllNetHotGame(retrofitManager.allNetHotGameRequest(typeId + 1)).enqueue(new MyCallback<ResponseBase<AllNetHotGameResponse>>() {
            @Override
            public void onSuccess(ResponseBase<AllNetHotGameResponse> model) {
                mAllNetHotGameResponse = model.getData_info();
                updataUi(mAllNetHotGameResponse);
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
            }
        });
    }

    private void updataUi(AllNetHotGameResponse data_info) {
        if (data_info == null) {
            return;
        }

        if (mAllNetHotGameResponse!=null)
            changeShowRefreshTime(mAllNetHotGameResponse.getLastTime());

        if (getUserVisibleHint()) {
            changeShowRefreshTime(data_info.getLastTime());
        }

        mDatas.clear();
        adapter.clearTempData();

        List<GameListBaseBean> dataList = data_info.getGameList();
        for (int i = 0; dataList != null && i < dataList.size(); i++) {
            mDatas.add(new AllNetHotGameAdapter.ViewBean(AllNetHotGameAdapter.ViewType.TYPE_GAME, dataList.get(i)));
        }

        adapter.notifyDataSetChanged();
    }

    public void changeDownloadStatus(DownloadEvent downloadEvent) {
        //        recommendTopDownloadTop.setTotalDownloadNum();//设置下载数

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));

            DownloadViewStrokeV2Big dowView = view.findViewById(R.id.itemDownloadBtn);
            if (dowView != null) {
                dowView.updateButn(table);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
